[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfoForEntity } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { BasicLayout } from '~/components/Layout/BasicLayout';
  21. import { PageView } from '~/components/PageView/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import type { RendererConfig } from '~/interfaces/services/renderer';
  26. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  27. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  28. import type { PageModel, PageDocument } from '~/server/models/page';
  29. import type { PageRedirectModel } from '~/server/models/page-redirect';
  30. import { useEditorModeClassName } from '~/services/layout/use-editor-mode-class-name';
  31. import {
  32. useCurrentUser,
  33. useIsForbidden, useIsSharedUser,
  34. useIsEnabledStaleNotification, useIsIdenticalPath,
  35. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  36. useDefaultIndentSize, useIsIndentSizeForced,
  37. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  38. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  39. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  40. useIsAllReplyShown, useIsContainerFluid, useIsNotCreatable,
  41. useIsUploadAllFileAllowed, useIsUploadEnabled, useReservedNextCaretLine,
  42. } from '~/stores-universal/context';
  43. import { useEditingMarkdown } from '~/stores/editor';
  44. import {
  45. useSWRxCurrentPage, useSWRMUTxCurrentPage, useCurrentPageId,
  46. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  47. } from '~/stores/page';
  48. import { useRedirectFrom } from '~/stores/page-redirect';
  49. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  50. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  51. import { useCurrentPageYjsData, useSWRMUTxCurrentPageYjsData } from '~/stores/yjs';
  52. import loggerFactory from '~/utils/logger';
  53. import type { NextPageWithLayout } from './_app.page';
  54. import type { CommonProps } from './utils/commons';
  55. import {
  56. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  57. } from './utils/commons';
  58. declare global {
  59. // eslint-disable-next-line vars-on-top, no-var
  60. var globalEmitter: EventEmitter;
  61. }
  62. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/client/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  63. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  64. const DisplaySwitcher = dynamic(() => import('~/client/components/Page/DisplaySwitcher').then(mod => mod.DisplaySwitcher), { ssr: false });
  65. const PageStatusAlert = dynamic(() => import('~/client/components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  66. const UnsavedAlertDialog = dynamic(() => import('~/client/components/UnsavedAlertDialog'), { ssr: false });
  67. const DescendantsPageListModal = dynamic(
  68. () => import('~/client/components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal),
  69. { ssr: false },
  70. );
  71. const DrawioModal = dynamic(() => import('~/client/components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  72. const HandsontableModal = dynamic(() => import('~/client/components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  73. const TemplateModal = dynamic(() => import('~/client/components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  74. const LinkEditModal = dynamic(() => import('~/client/components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  75. const TagEditModal = dynamic(() => import('~/client/components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  76. const ConflictDiffModal = dynamic(() => import('~/client/components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  77. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  78. const EditablePageEffects = dynamic(() => import('~/client/components/Page/EditablePageEffects').then(mod => mod.EditablePageEffects), { ssr: false });
  79. const logger = loggerFactory('growi:pages:all');
  80. const {
  81. isPermalink: _isPermalink, isCreatablePage,
  82. } = pagePathUtils;
  83. const { removeHeadingSlash } = pathUtils;
  84. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  85. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  86. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  87. {
  88. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  89. return v?.data != null
  90. && v?.data.toObject != null
  91. && v?.meta != null
  92. && isIPageInfoForEntity(v.meta);
  93. },
  94. serialize: (v) => {
  95. return {
  96. data: superjson.stringify(v.data.toObject()),
  97. meta: superjson.stringify(v.meta),
  98. };
  99. },
  100. deserialize: (v) => {
  101. return {
  102. data: superjson.parse(v.data),
  103. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  104. };
  105. },
  106. },
  107. 'IPageToShowRevisionWithMetaTransformer',
  108. );
  109. // GrowiContextualSubNavigation for NOT shared page
  110. type GrowiContextualSubNavigationProps = {
  111. isLinkSharingDisabled: boolean,
  112. }
  113. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  114. const { isLinkSharingDisabled } = props;
  115. const { data: currentPage } = useSWRxCurrentPage();
  116. return (
  117. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  118. );
  119. };
  120. type Props = CommonProps & {
  121. pageWithMeta: IPageToShowRevisionWithMeta | null,
  122. // pageUser?: any,
  123. redirectFrom?: string;
  124. // shareLinkId?: string;
  125. isLatestRevision?: boolean,
  126. isIdenticalPathPage?: boolean,
  127. isForbidden: boolean,
  128. isNotFound: boolean,
  129. isNotCreatable: boolean,
  130. // isAbleToDeleteCompletely: boolean,
  131. templateTagData?: string[],
  132. templateBodyData?: string,
  133. isSearchServiceConfigured: boolean,
  134. isSearchServiceReachable: boolean,
  135. isSearchScopeChildrenAsDefault: boolean,
  136. isEnabledMarp: boolean,
  137. sidebarConfig: ISidebarConfig,
  138. isSlackConfigured: boolean,
  139. // isMailerSetup: boolean,
  140. isAclEnabled: boolean,
  141. // hasSlackConfig: boolean,
  142. drawioUri: string | null,
  143. noCdn: string,
  144. // highlightJsStyle: string,
  145. isAllReplyShown: boolean,
  146. isContainerFluid: boolean,
  147. isUploadEnabled: boolean,
  148. isUploadAllFileAllowed: boolean,
  149. isEnabledStaleNotification: boolean,
  150. isEnabledAttachTitleHeader: boolean,
  151. // isEnabledLinebreaks: boolean,
  152. // isEnabledLinebreaksInComments: boolean,
  153. adminPreferredIndentSize: number,
  154. isIndentSizeForced: boolean,
  155. disableLinkSharing: boolean,
  156. skipSSR: boolean,
  157. ssrMaxRevisionBodyLength: number,
  158. yjsData: CurrentPageYjsData,
  159. rendererConfig: RendererConfig,
  160. };
  161. const Page: NextPageWithLayout<Props> = (props: Props) => {
  162. // register global EventEmitter
  163. if (isClient() && window.globalEmitter == null) {
  164. window.globalEmitter = new EventEmitter();
  165. }
  166. const router = useRouter();
  167. useCurrentUser(props.currentUser ?? null);
  168. // commons
  169. useCsrfToken(props.csrfToken);
  170. useGrowiCloudUri(props.growiCloudUri);
  171. // page
  172. useIsContainerFluid(props.isContainerFluid);
  173. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  174. useIsForbidden(props.isForbidden);
  175. useIsNotCreatable(props.isNotCreatable);
  176. useRedirectFrom(props.redirectFrom ?? null);
  177. useIsSharedUser(false); // this page cann't be routed for '/share'
  178. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  179. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  180. useIsSearchPage(false);
  181. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  182. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  183. useIsSearchServiceReachable(props.isSearchServiceReachable);
  184. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  185. useIsSlackConfigured(props.isSlackConfigured);
  186. // useIsMailerSetup(props.isMailerSetup);
  187. useIsAclEnabled(props.isAclEnabled);
  188. // useHasSlackConfig(props.hasSlackConfig);
  189. // useNoCdn(props.noCdn);
  190. useDefaultIndentSize(props.adminPreferredIndentSize);
  191. useIsIndentSizeForced(props.isIndentSizeForced);
  192. useDisableLinkSharing(props.disableLinkSharing);
  193. useRendererConfig(props.rendererConfig);
  194. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  195. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  196. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  197. useIsAllReplyShown(props.isAllReplyShown);
  198. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  199. useIsUploadEnabled(props.isUploadEnabled);
  200. const { pageWithMeta } = props;
  201. const pageId = pageWithMeta?.data._id;
  202. const revisionBody = pageWithMeta?.data.revision?.body;
  203. useCurrentPathname(props.currentPathname);
  204. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  205. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  206. const { trigger: mutateCurrentPageYjsDataFromApi } = useSWRMUTxCurrentPageYjsData();
  207. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  208. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  209. const { mutate: mutateIsNotFound } = useIsNotFound();
  210. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  211. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  212. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  213. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  214. const { mutate: mutateCurrentPageYjsData } = useCurrentPageYjsData();
  215. useSetupGlobalSocket();
  216. useSetupGlobalSocketForPage(pageId);
  217. useReservedNextCaretLine();
  218. // Store initial data (When revisionBody is not SSR)
  219. useEffect(() => {
  220. if (!props.skipSSR) {
  221. return;
  222. }
  223. if (currentPageId != null && !props.isNotFound) {
  224. const mutatePageData = async() => {
  225. const pageData = await mutateCurrentPage();
  226. mutateEditingMarkdown(pageData?.revision?.body);
  227. mutateCurrentPageYjsDataFromApi();
  228. };
  229. // If skipSSR is true, use the API to retrieve page data.
  230. // Because pageWIthMeta does not contain revision.body
  231. mutatePageData();
  232. }
  233. }, [currentPageId, mutateCurrentPage, mutateCurrentPageYjsDataFromApi, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  234. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  235. useEffect(() => {
  236. const decodedURI = decodeURI(window.location.pathname);
  237. if (isClient() && decodedURI !== props.currentPathname) {
  238. const { search, hash } = window.location;
  239. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  240. }
  241. }, [props.currentPathname, router]);
  242. // initialize mutateEditingMarkdown only once per page
  243. // need to include useCurrentPathname not useCurrentPagePath
  244. useEffect(() => {
  245. if (props.currentPathname != null) {
  246. mutateEditingMarkdown(revisionBody);
  247. }
  248. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  249. useEffect(() => {
  250. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  251. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  252. useEffect(() => {
  253. mutateCurrentPageId(pageId ?? null);
  254. }, [mutateCurrentPageId, pageId]);
  255. useEffect(() => {
  256. mutateIsNotFound(props.isNotFound);
  257. }, [mutateIsNotFound, props.isNotFound]);
  258. useEffect(() => {
  259. mutateIsLatestRevision(props.isLatestRevision);
  260. }, [mutateIsLatestRevision, props.isLatestRevision]);
  261. useEffect(() => {
  262. mutateTemplateTagData(props.templateTagData);
  263. }, [props.templateTagData, mutateTemplateTagData]);
  264. useEffect(() => {
  265. mutateTemplateBodyData(props.templateBodyData);
  266. }, [props.templateBodyData, mutateTemplateBodyData]);
  267. useEffect(() => {
  268. mutateCurrentPageYjsData(props.yjsData);
  269. }, [mutateCurrentPageYjsData, props.yjsData]);
  270. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  271. // So preferentially take page data from useSWRxCurrentPage
  272. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  273. const title = generateCustomTitleForPage(props, pagePath);
  274. return (
  275. <>
  276. <Head>
  277. <title>{title}</title>
  278. </Head>
  279. <div className="dynamic-layout-root justify-content-between">
  280. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  281. <PageView
  282. className="d-edit-none"
  283. pagePath={pagePath}
  284. initialPage={pageWithMeta?.data}
  285. rendererConfig={props.rendererConfig}
  286. />
  287. <EditablePageEffects />
  288. <DisplaySwitcher />
  289. <PageStatusAlert />
  290. </div>
  291. </>
  292. );
  293. };
  294. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  295. const editorModeClassName = useEditorModeClassName();
  296. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  297. };
  298. type LayoutProps = Props & {
  299. children?: ReactNode
  300. }
  301. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  302. // init sidebar config with UserUISettings and sidebarConfig
  303. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  304. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  305. };
  306. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  307. return (
  308. <>
  309. <GrowiPluginsActivator />
  310. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  311. <Layout {...page.props}>
  312. {page}
  313. </Layout>
  314. <UnsavedAlertDialog />
  315. <DescendantsPageListModal />
  316. <DrawioModal />
  317. <HandsontableModal />
  318. <QuestionnaireModalManager />
  319. <TemplateModal />
  320. <LinkEditModal />
  321. <TagEditModal />
  322. <ConflictDiffModal />
  323. </>
  324. );
  325. };
  326. function getPageIdFromPathname(currentPathname: string): string | null {
  327. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  328. }
  329. class MultiplePagesHitsError extends ExtensibleCustomError {
  330. pagePath: string;
  331. constructor(pagePath: string) {
  332. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  333. this.pagePath = pagePath;
  334. }
  335. }
  336. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  337. const { model: mongooseModel } = await import('mongoose');
  338. const req: CrowiRequest = context.req as CrowiRequest;
  339. const { crowi } = req;
  340. const { revisionId } = req.query;
  341. const Page = crowi.model('Page') as PageModel;
  342. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  343. const { pageService, configManager } = crowi;
  344. let currentPathname = props.currentPathname;
  345. const pageId = getPageIdFromPathname(currentPathname);
  346. const isPermalink = _isPermalink(currentPathname);
  347. const { user } = req;
  348. if (!isPermalink) {
  349. // check redirects
  350. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  351. if (chains != null) {
  352. // overwrite currentPathname
  353. currentPathname = chains.end.toPath;
  354. props.currentPathname = currentPathname;
  355. // set redirectFrom
  356. props.redirectFrom = chains.start.fromPath;
  357. }
  358. // check whether the specified page path hits to multiple pages
  359. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  360. if (count > 1) {
  361. throw new MultiplePagesHitsError(currentPathname);
  362. }
  363. }
  364. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  365. const page = pageWithMeta?.data as unknown as PageDocument;
  366. // add user to seen users
  367. if (page != null && user != null) {
  368. await page.seen(user);
  369. }
  370. // populate & check if the revision is latest
  371. if (page != null) {
  372. page.initLatestRevisionField(revisionId);
  373. props.isLatestRevision = page.isLatestRevision();
  374. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  375. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  376. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  377. }
  378. props.pageWithMeta = pageWithMeta;
  379. }
  380. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  381. const req: CrowiRequest = context.req as CrowiRequest;
  382. const { crowi } = req;
  383. const Page = crowi.model('Page') as PageModel;
  384. const { currentPathname } = props;
  385. const pageId = getPageIdFromPathname(currentPathname);
  386. const isPermalink = _isPermalink(currentPathname);
  387. const page = props.pageWithMeta?.data;
  388. if (props.isIdenticalPathPage) {
  389. props.isNotCreatable = true;
  390. }
  391. else if (page == null) {
  392. props.isNotFound = true;
  393. props.isNotCreatable = !isCreatablePage(currentPathname);
  394. // check the page is forbidden or just does not exist.
  395. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  396. props.isForbidden = count > 0;
  397. }
  398. else {
  399. props.isNotFound = page.isEmpty;
  400. props.isNotCreatable = false;
  401. props.isForbidden = false;
  402. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  403. if (isPermalink && page.isEmpty) {
  404. props.currentPathname = page.path;
  405. }
  406. // /path/to/page ==> /62a88db47fed8b2d94f30000
  407. if (!isPermalink && !page.isEmpty) {
  408. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  409. if (!isToppage) {
  410. props.currentPathname = `/${page._id}`;
  411. }
  412. }
  413. if (!props.skipSSR) {
  414. props.yjsData = await crowi.pageService.getYjsData(page._id.toString());
  415. }
  416. }
  417. }
  418. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  419. // const req: CrowiRequest = context.req as CrowiRequest;
  420. // const { crowi } = req;
  421. // const UserModel = crowi.model('User');
  422. // if (isUserPage(props.currentPagePath)) {
  423. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  424. // if (user != null) {
  425. // props.pageUser = JSON.stringify(user.toObject());
  426. // }
  427. // }
  428. // }
  429. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  430. const req: CrowiRequest = context.req as CrowiRequest;
  431. const { crowi } = req;
  432. const {
  433. searchService, configManager, aclService,
  434. } = crowi;
  435. props.isSearchServiceConfigured = searchService.isConfigured;
  436. props.isSearchServiceReachable = searchService.isReachable;
  437. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  438. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  439. // props.isMailerSetup = mailService.isMailerSetup;
  440. props.isAclEnabled = aclService.isAclEnabled();
  441. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  442. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  443. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  444. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  445. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  446. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  447. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  448. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  449. props.isUploadAllFileAllowed = crowi.fileUploadService.getFileUploadEnabled();
  450. props.isUploadEnabled = crowi.fileUploadService.getIsUploadable();
  451. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  452. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  453. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  454. props.sidebarConfig = {
  455. isSidebarCollapsedMode: configManager.getConfig('crowi', 'customize:isSidebarCollapsedMode'),
  456. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  457. };
  458. props.rendererConfig = {
  459. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  460. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  461. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  462. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  463. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  464. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  465. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  466. // XSS Options
  467. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  468. sanitizeType: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  469. customAttrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  470. customTagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  471. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  472. };
  473. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  474. }
  475. /**
  476. * for Server Side Translations
  477. * @param context
  478. * @param props
  479. * @param namespacesRequired
  480. */
  481. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  482. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  483. props._nextI18Next = nextI18NextConfig._nextI18Next;
  484. }
  485. const getAction = (props: Props): SupportedActionType => {
  486. if (props.isNotCreatable) {
  487. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  488. }
  489. if (props.isForbidden) {
  490. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  491. }
  492. if (props.isNotFound) {
  493. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  494. }
  495. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  496. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  497. }
  498. return SupportedAction.ACTION_PAGE_VIEW;
  499. };
  500. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  501. const req = context.req as CrowiRequest;
  502. const { user } = req;
  503. const result = await getServerSideCommonProps(context);
  504. // check for presence
  505. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  506. if (!('props' in result)) {
  507. throw new Error('invalid getSSP result');
  508. }
  509. const props: Props = result.props as Props;
  510. if (props.redirectDestination != null) {
  511. return {
  512. redirect: {
  513. permanent: false,
  514. destination: props.redirectDestination,
  515. },
  516. };
  517. }
  518. if (user != null) {
  519. props.currentUser = user.toObject();
  520. }
  521. try {
  522. await injectPageData(context, props);
  523. }
  524. catch (err) {
  525. if (err instanceof MultiplePagesHitsError) {
  526. props.isIdenticalPathPage = true;
  527. }
  528. else {
  529. throw err;
  530. }
  531. }
  532. await injectRoutingInformation(context, props);
  533. injectServerConfigurations(context, props);
  534. await injectNextI18NextConfigurations(context, props, ['translation']);
  535. addActivity(context, getAction(props));
  536. return {
  537. props,
  538. };
  539. };
  540. export default Page;